package middleware

import (
	"net/http"

	"github.com/ecodeclub/ginx"
	"github.com/ecodeclub/ginx/session"
	"github.com/gin-gonic/gin"
	"github.com/gotomicro/ego/core/elog"
)

type AuthMiddlewareBuilder struct {
	logger *elog.Component
	sp     session.Provider
}

func NewAuthMiddlewareBuilder() *AuthMiddlewareBuilder {
	return &AuthMiddlewareBuilder{
		logger: elog.DefaultLogger,
	}
}

func (c *AuthMiddlewareBuilder) Build() gin.HandlerFunc {
	if c.sp == nil {
		c.sp = session.DefaultProvider()
	}
	return func(ctx *gin.Context) {
		gctx := &ginx.Context{Context: ctx}
		_, err := c.sp.Get(gctx)
		if err != nil {
			gctx.AbortWithStatus(http.StatusForbidden)
			c.logger.Debug("用户未登录", elog.FieldErr(err))
			return
		}
	}
}
